﻿#region Copyright(C) 2013 NCS Pte. Ltd. All rights reserved.

// ==================================================================================================
// Copyright(C) 2013 NCS Pte. Ltd. All rights reserved.
//
// SYSTEM NAME	:   iConnect.Azure Application Framework
// COMPONENT ID :   NCS.IConnect.Azure.Diagnostics.CloudServiceRuntime.WorkerEntryPoint
// COMPONENT DESC:  	
//
// CREATED DATE/BY:  20 Dec 2012 / Lu Ya Ming
//
// REVISION HISTORY:	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================

#endregion

using System;
using System.Diagnostics;

namespace NCS.IConnect.Cloud.Core.CloudServiceRuntime
{
    /// <summary>
    /// The worker entry point to invoke from WorkRole.
    /// </summary>
    public class WorkerEntryPoint
    {
        /// <summary>
        /// Called when [start].
        /// </summary>
        /// <returns></returns>
        public virtual bool OnStart()
        {
            return true;
        }

        /// <summary>
        /// This method prevents unhandled exceptions from being thrown
        /// from the worker thread.
        /// </summary>
        internal void ProtectedRun()
        {
            try
            {
                // Call the Workers Run() method
                Run();
            }
            catch (SystemException ex)
            {
                // Performs Error Logging or Diagnostic
                LogErrors(ex);
                // Exit Quickly on a System Exception
                throw ex;
            }
            catch (Exception ex)
            {
                // Performs Error Logging or Diagnostic
                LogErrors(ex);
            }
        }

        /// <summary>
        /// Runs the current worker.
        /// </summary>
        public virtual void Run()
        {
        }

        /// <summary>
        /// Stops the current worker.
        /// </summary>
        public virtual void OnStop()
        {
        }

        /// <summary>
        /// Logs the errors from application level.
        /// </summary>
        public virtual void LogErrors(Exception ex)
        {
            Trace.WriteLine(ex.ToString());
        }

    }
}
